package com.drama.api.sys.video.service.impl;

import cn.hutool.core.date.DateUtil;
import com.drama.api.base.Constants;
import com.drama.api.base.Type;
import com.drama.api.company.company.dao.CompanyDao;
import com.drama.api.company.company.domain.po.CompanyPO;
import com.drama.api.company.dramas.dao.CompanyDramasDao;
import com.drama.api.company.dramas.domain.po.CompanyDramasPO;
import com.drama.api.sys.dramas.dao.SysDramasDao;
import com.drama.api.sys.dramas.dao.SysVideoDao;
import com.drama.api.sys.dramas.domain.po.SysDramasPO;
import com.drama.api.sys.dramas.domain.po.SysVideoPO;
import com.drama.api.sys.video.dao.ResourceFileDao;
import com.drama.api.sys.video.dao.VideoTaskDao;
import com.drama.api.sys.video.domain.po.ResourceFilePO;
import com.drama.api.sys.video.domain.po.VideoTaskPO;
import com.drama.api.sys.video.domain.vo.VideoTaskSearchVO;
import com.drama.api.sys.video.domain.vo.VideoTaskVO;
import com.drama.api.sys.video.service.IVideoTaskService;
import com.drama.api.task.DeleteFileThread;
import com.drama.exception.BusinessException;
import com.drama.util.MpcUtils;
import com.drama.util.RestTemplateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


@Service
@Transactional
@Slf4j
public class VideoTaskServiceImpl implements IVideoTaskService {

    @Autowired
    private SysDramasDao sysDramasDao;
    @Autowired
    private SysVideoDao sysVideoDao;
    @Autowired
    private ResourceFileDao resourceFileDao;
    @Autowired
    private  VideoTaskDao videoTaskDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private CompanyDramasDao companyDramasDao;

    @Value("${resource.api.url}")
    private String resource_server_url;

//    @Autowired
//    private ICompanyDramasService companyDramasService;

    @Override
    public List<VideoTaskVO> getList(VideoTaskSearchVO searchVO) {
        if(searchVO.getTaskType()==null){
            searchVO.setTaskType(1);
        }
        return videoTaskDao.getList(searchVO);
    }

    @Override
    public void add(String id) {
        String task_id = getTaskId(id);
        VideoTaskPO videoTaskPO=new VideoTaskPO();
        videoTaskPO.setVideoId(id);
        if(StringUtils.isNotBlank(task_id)){
            videoTaskPO.setTaskId(task_id);
            videoTaskPO.setTaskState(1);
        }else{
            videoTaskPO.setTaskState(3);
        }
        videoTaskPO.setTaskType(1);
        videoTaskPO.preInsert();
        int i = videoTaskDao.insertSelective(videoTaskPO);
        if (i == Constants.SQL_RETURN_SUCCESS) {
            throw new BusinessException(Type.FAIL);
        }
    }

    @Override
    public void addDrama(String id) {
        SysDramasPO sysDramasPO = sysDramasDao.selectByPrimaryKey(id);
        if (sysDramasPO == null) {
            throw new BusinessException(Type.FAIL.getCode(), "需要转码的视频剧集不存在！");
        }
        ResourceFilePO resourceFilePO = resourceFileDao.selectByPrimaryKey(sysDramasPO.getDramaFileId());
        if (resourceFilePO == null) {
            throw new BusinessException(Type.FAIL.getCode(), "转码文件不存在！");
        }
        if (resourceFilePO.getFileFullPath().indexOf("http://video.yujuyi.com") == -1) {
            throw new BusinessException(Type.FAIL.getCode(), "文件地址不支持转码！");
        }
        String task_id=MpcUtils.CreateTranscodingTask(resourceFilePO.getFileRealPath(), "video/" + sysDramasPO.getCompanyId(), sysDramasPO.getId());
        VideoTaskPO videoTaskPO=new VideoTaskPO();
        videoTaskPO.setDramasId(id);
        if(StringUtils.isNotBlank(task_id)){
            videoTaskPO.setTaskId(task_id);
            videoTaskPO.setTaskState(1);
        }else{
            videoTaskPO.setTaskState(3);
        }
        videoTaskPO.setTaskType(2);
        videoTaskPO.preInsert();
        int i = videoTaskDao.insertSelective(videoTaskPO);
        if (i == Constants.SQL_RETURN_SUCCESS) {
            throw new BusinessException(Type.FAIL);
        }
    }

    @Override
    public void reset(String id) {
        VideoTaskPO videoTaskPO=videoTaskDao.selectByPrimaryKey(id);
        if(videoTaskPO==null){
            throw new BusinessException(Type.FAIL.getCode(), "转码任务不存在！");
        }
        if(videoTaskPO.getTaskState()!=3){
            throw new BusinessException(Type.FAIL.getCode(), "当前状态不允许重启！");
        }
        String task_id = getTaskId(videoTaskPO.getVideoId());
        if(StringUtils.isNotBlank(task_id)){
            videoTaskPO.setTaskId(task_id);
            videoTaskPO.setTaskState(1);
        }else{
            videoTaskPO.setTaskState(3);
        }
        videoTaskPO.preUpdate();
        int i = videoTaskDao.updateByPrimaryKeySelective(videoTaskPO);
        if (i == Constants.SQL_RETURN_SUCCESS) {
            throw new BusinessException(Type.FAIL);
        }
    }

    @Override
    public void opAction(String taskId, String status, String outPath, String outFileName, String fileSize, String rate) {
        Example example = new Example(VideoTaskPO.class);
        example.and().andEqualTo("taskId",taskId);
        VideoTaskPO videoTaskPO=videoTaskDao.selectOneByExample(example);
        if(videoTaskPO==null){
            return;//任务不存在返回
        }
        if(status.equals("SUCCEEDED")){
            videoTaskPO.setTaskState(2);
            String companyId="";
            CompanyPO companyPO=new CompanyPO();
            if(videoTaskPO.getTaskType()==1){
                SysVideoPO sysVideoPO = sysVideoDao.selectByPrimaryKey(videoTaskPO.getVideoId());
                CompanyDramasPO sysDramasPO = companyDramasDao.selectByPrimaryKey(sysVideoPO.getDramaId());
                companyPO= companyDao.selectByPrimaryKey(sysDramasPO.getCompanyId());
                if(StringUtils.isNotBlank(sysVideoPO.getVideoUrl())){
                    //释放原来的资源
                    companyPO.setStorageNum(new BigDecimal(companyPO.getStorageNum()).subtract(sysVideoPO.getVideoSize()).toString());
                    //TODO 删除资源
                    Constants.executor.execute(new DeleteFileThread(new RestTemplateUtils(),resource_server_url,sysVideoPO.getVideoUrl()));
                }
                sysVideoPO.setVideoUrl("http://video.yujuyi.com/"+outPath+"/"+outFileName);
                sysVideoPO.setVideoSize(new BigDecimal(fileSize));
                sysVideoPO.setVideoTranscodingState(1);
                sysVideoPO.setVideoRate(new BigDecimal(rate));
                sysVideoPO.preUpdate();
                sysVideoDao.updateByPrimaryKeySelective(sysVideoPO);
//                companyDramasService.addDramasSchedule(sysDramasPO,sysVideoPO.getUpdateDate(),"平台转码完成",3);
            }
            if(videoTaskPO.getTaskType()==2){
                SysDramasPO sysDramasPO = sysDramasDao.selectByPrimaryKey(videoTaskPO.getDramasId());
                companyPO= companyDao.selectByPrimaryKey(sysDramasPO.getCompanyId());
                if(StringUtils.isNotBlank(sysDramasPO.getDramaUrl())&&StringUtils.isNotBlank(sysDramasPO.getRemarks())){
                    companyPO.setStorageNum(new BigDecimal(companyPO.getStorageNum()).subtract(new BigDecimal(sysDramasPO.getRemarks())).toString());
//                    ResourceFilePO companyFilePO=resourceFileDao.selectByPrimaryKey(sysDramasPO.getDramaFileId());
//                    if(!companyFilePO.getFileFullPath().equals(sysDramasPO.getDramaUrl())){
//                        TODO 删除资源
//                        Constants.executor.execute(new DeleteFileThread(new RestTemplateUtils(),resource_server_url,sysDramasPO.getDramaUrl()));
//                    }
                }
                sysDramasPO.setDramaUrl("http://video.yujuyi.com/"+outPath+"/"+outFileName);
                sysDramasPO.setDramaRate(new BigDecimal(rate));
                sysDramasPO.setRemarks(fileSize);
                sysDramasDao.updateByPrimaryKeySelective(sysDramasPO);
            }
            companyPO.setStorageNum(new BigDecimal(companyPO.getStorageNum()).add(new BigDecimal(fileSize)).toString());
            companyDao.updateByPrimaryKeySelective(companyPO);
        }else {
            videoTaskPO.setTaskState(3);
        }
        videoTaskDao.updateByPrimaryKeySelective(videoTaskPO);
    }



    private String getTaskId(String videoId) {
        SysVideoPO sysVideoPO = sysVideoDao.selectByPrimaryKey(videoId);
        if (sysVideoPO == null) {
            throw new BusinessException(Type.FAIL.getCode(), "需要转码的视频不存在！");
        }
        SysDramasPO sysDramasPO = sysDramasDao.selectByPrimaryKey(sysVideoPO.getDramaId());
        if (sysDramasPO == null) {
            throw new BusinessException(Type.FAIL.getCode(), "需要转码的视频剧集不存在！");
        }
        ResourceFilePO resourceFilePO = resourceFileDao.selectByPrimaryKey(sysVideoPO.getVideoFileId());
        if (resourceFilePO == null) {
            throw new BusinessException(Type.FAIL.getCode(), "转码文件不存在！");
        }
        if (resourceFilePO.getFileFullPath().indexOf("http://video.yujuyi.com") == -1) {
            throw new BusinessException(Type.FAIL.getCode(), "文件地址不支持转码！");
        }
        return MpcUtils.CreateTranscodingTask(resourceFilePO.getFileRealPath(), "video/" + sysDramasPO.getCompanyId(), sysVideoPO.getId()+DateUtil.format(new Date(),"yyyyMMddHHmmss"), sysDramasPO.getDramaNo());
    }
}